// menu.go - 菜单管理模块
// pkg/menu.go - 菜单管理模块
package pkg

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// ShowMenu 显示菜单
func (rct *RemoteControlTool) ShowMenu() {
	fmt.Println("\n" + strings.Repeat("=", 70))
	fmt.Println("                           远程控制工具")
	fmt.Println(strings.Repeat("=", 70))
	fmt.Println("1. 列出所有主机")
	fmt.Println("2. 添加新主机")
	fmt.Println("3. 修改主机信息")
	fmt.Println("4. 删除主机")
	fmt.Println("5. 导入主机")
	fmt.Println("6. 执行命令")
	fmt.Println("7. 导入命令")
	fmt.Println("8. 配置选项")
	fmt.Println("9. 退出程序")
	fmt.Println(strings.Repeat("=", 70))
}

// HandleMenu 处理菜单选择
func (rct *RemoteControlTool) HandleMenu(choice string) bool {
	switch choice {
	case "1":
		rct.handleListHosts()
	case "2":
		rct.handleAddHost()
	case "3":
		rct.handleUpdateHost()
	case "4":
		rct.handleDeleteHost()
	case "5":
		rct.handleImportHostsFromFile()
	case "7":
		rct.handleExecuteCommandsFromFile()
	case "6":
		rct.handleExecuteCommand()
	case "8":
		rct.handleConfig()
	case "9":
		fmt.Println("程序已退出")
		return false
	default:
		fmt.Println("无效选择，请输入1-9之间的数字")
	}
	return true
}

// handleListHosts 处理列出主机
func (rct *RemoteControlTool) handleListHosts() {
	fmt.Println("\n主机列表:")
	hosts, err := rct.GetHosts()
	if err != nil {
		fmt.Printf("获取主机列表失败: %v\n", err)
		return
	}
	if len(hosts) == 0 {
		fmt.Println("  没有配置任何主机")
	} else {
		fmt.Printf("%-5s %-15s %-10s %-5s\n", "ID", "IP", "用户", "端口")
		fmt.Println(strings.Repeat("-", 50))
		for _, host := range hosts {
			fmt.Printf("%-5d %-15s %-10s %-5d\n",
				host.ID, host.IP, host.User, host.Port)
		}
	}
}

// handleAddHost 处理添加主机
func (rct *RemoteControlTool) handleAddHost() {
	fmt.Println("\n添加新主机:")
	ip := rct.ReadInput("输入IP: ")
	if ip == "" {
		fmt.Println("IP不能为空")
		return
	}
	portInput := rct.ReadInput("输入端口 (默认22): ")
	port := 22
	if portInput != "" {
		fmt.Sscanf(portInput, "%d", &port)
	}
	user := rct.ReadInput("输入用户名: ")
	if user == "" {
		fmt.Println("用户名不能为空")
		return
	}
	password := rct.ReadInput("输入密码: ")
	if password == "" {
		fmt.Println("密码不能为空")
		return
	}
	rootPass := rct.ReadInput("输入root密码 (可选，直接回车跳过): ")

	host := HostInfo{
		IP:       ip,
		Port:     port,
		User:     user,
		Password: password,
		RootPass: rootPass,
	}

	err := rct.AddHost(host)
	if err != nil {
		fmt.Printf("添加主机失败: %v\n", err)
	} else {
		fmt.Println("主机添加成功")
	}
}

// handleUpdateHost 处理修改主机
func (rct *RemoteControlTool) handleUpdateHost() {
	rct.handleListHosts()
	idStr := rct.ReadInput("\n请输入要修改的主机ID: ")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		fmt.Println("无效的主机ID")
		return
	}

	host, err := rct.GetHostByID(id)
	if err != nil {
		fmt.Printf("未找到ID为 %d 的主机\n", id)
		return
	}

	fmt.Printf("当前信息 -> IP: %s, 端口: %d, 用户: %s\n", host.IP, host.Port, host.User)
	newIP := rct.ReadInput("新IP (回车保持不变): ")
	if newIP != "" {
		host.IP = newIP
	}
	newPortStr := rct.ReadInput("新端口 (回车保持不变): ")
	if newPortStr != "" {
		fmt.Sscanf(newPortStr, "%d", &host.Port)
	}
	newUser := rct.ReadInput("新用户名 (回车保持不变): ")
	if newUser != "" {
		host.User = newUser
	}
	newPass := rct.ReadInput("新密码 (回车保持不变): ")
	if newPass != "" {
		host.Password = newPass
	}
	newRootPass := rct.ReadInput("新root密码 (回车保持不变): ")
	if newRootPass != "" {
		host.RootPass = newRootPass
	}

	err = rct.UpdateHost(id, *host)
	if err != nil {
		fmt.Printf("更新主机失败: %v\n", err)
	} else {
		fmt.Println("主机信息更新成功")
	}
}

// handleDeleteHost 处理删除主机
func (rct *RemoteControlTool) handleDeleteHost() {
	rct.handleListHosts()
	idStr := rct.ReadInput("\n请输入要删除的主机ID: ")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		fmt.Println("无效的主机ID")
		return
	}

	confirm := rct.ReadInput(fmt.Sprintf("确认删除主机ID %d? (y/n): ", id))
	if strings.ToLower(confirm) != "y" && strings.ToLower(confirm) != "yes" {
		fmt.Println("操作已取消")
		return
	}

	err = rct.DeleteHost(id)
	if err != nil {
		fmt.Printf("删除主机失败: %v\n", err)
	} else {
		fmt.Println("主机删除成功")
	}
}

// handleImportHostsFromFile 处理从文件导入主机
func (rct *RemoteControlTool) handleImportHostsFromFile() {
	fmt.Println("\n从文件导入主机:")
	filePath := rct.ReadInput("请输入主机信息文件路径 (txt格式): ")
	if filePath == "" {
		fmt.Println("文件路径不能为空")
		return
	}
	err := rct.ImportHostsFromTxt(filePath)
	if err != nil {
		fmt.Printf("从文件导入主机失败: %v\n", err)
	} else {
		fmt.Println("主机导入成功")
	}
}

// handleExecuteCommandsFromFile 处理从文件执行命令
func (rct *RemoteControlTool) handleExecuteCommandsFromFile() {
	fmt.Println("\n从文件导入命令并执行:")

	hosts, err := rct.GetHosts()
	if err != nil {
		fmt.Printf("获取主机列表失败: %v\n", err)
		return
	}
	if len(hosts) == 0 {
		fmt.Println("没有配置任何主机")
		return
	}

	fmt.Printf("%-5s %-15s %-10s %-5s\n", "ID", "IP", "用户", "端口")
	fmt.Println(strings.Repeat("-", 50))
	for _, host := range hosts {
		fmt.Printf("%-5d %-15s %-10s %-5d\n",
			host.ID, host.IP, host.User, host.Port)
	}

	fmt.Println("\n主机选择说明:")
	fmt.Println("- 单个主机: 输入主机ID (例如: 1)")
	fmt.Println("- 多个主机: 用逗号分隔 (例如: 1,3,5)")
	fmt.Println("- 范围主机: 用连字符表示范围 (例如: 1-3)")
	fmt.Println("- 全部主机: 输入 'all'")
	fmt.Println("- 组合使用: 1,3-5,7 表示主机1,3,4,5,7")

	selection := rct.ReadInput("请选择主机 (输入ID或范围，或输入'all'执行所有主机): ")
	if selection == "" {
		fmt.Println("选择不能为空")
		return
	}

	var hostIDs []int
	if strings.ToLower(selection) == "all" {
		for _, host := range hosts {
			hostIDs = append(hostIDs, host.ID)
		}
	} else {
		var err error
		hostIDs, err = rct.ParseHostSelection(selection)
		if err != nil {
			fmt.Printf("主机选择解析失败: %v\n", err)
			return
		}
	}

	filePath := rct.ReadInput("请输入命令文件路径 (txt格式): ")
	if filePath == "" {
		fmt.Println("文件路径不能为空")
		return
	}

	file, err := os.Open(filePath)
	if err != nil {
		fmt.Printf("打开命令文件失败: %v\n", err)
		return
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	var commands []string
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line != "" && !strings.HasPrefix(line, "#") {
			commands = append(commands, line)
		}
	}

	if len(commands) == 0 {
		fmt.Println("命令文件中没有找到有效命令")
		return
	}

	fmt.Println("\n执行权限选择:")
	fmt.Println("1. 普通用户执行")
	fmt.Println("2. Root用户执行")

	privilegeChoice := rct.ReadInput("请选择执行权限 (1-2): ")
	var useRoot bool

	switch privilegeChoice {
	case "1":
		useRoot = false
		fmt.Println("使用普通用户权限执行")
	case "2":
		useRoot = true
		fmt.Println("使用root权限执行")
	default:
		fmt.Println("无效选择，默认使用普通用户权限执行")
		useRoot = false
	}

	allResults := rct.ExecuteMultipleCommandsOnSelectedHosts(hostIDs, commands, useRoot)
	rct.PrintMultipleResults(allResults, commands)
}

// handleExecuteCommand 处理执行命令
func (rct *RemoteControlTool) handleExecuteCommand() {
	fmt.Println("\n在主机上执行命令:")

	hosts, err := rct.GetHosts()
	if err != nil {
		fmt.Printf("获取主机列表失败: %v\n", err)
		return
	}
	if len(hosts) == 0 {
		fmt.Println("没有配置任何主机")
		return
	}

	fmt.Printf("%-5s %-15s %-10s %-5s\n", "ID", "IP", "用户", "端口")
	fmt.Println(strings.Repeat("-", 50))
	for _, host := range hosts {
		fmt.Printf("%-5d %-15s %-10s %-5d\n",
			host.ID, host.IP, host.User, host.Port)
	}

	fmt.Println("\n主机选择说明:")
	fmt.Println("- 单个主机: 输入主机ID (例如: 1)")
	fmt.Println("- 多个主机: 用逗号分隔 (例如: 1,3,5)")
	fmt.Println("- 范围主机: 用连字符表示范围 (例如: 1-3)")
	fmt.Println("- 全部主机: 输入 'all'")
	fmt.Println("- 组合使用: 1,3-5,7 表示主机1,3,4,5,7")

	selection := rct.ReadInput("请选择主机 (输入ID或范围，或输入'all'执行所有主机): ")
	if selection == "" {
		fmt.Println("选择不能为空")
		return
	}

	var hostIDs []int
	if strings.ToLower(selection) == "all" {
		for _, host := range hosts {
			hostIDs = append(hostIDs, host.ID)
		}
	} else {
		var err error
		hostIDs, err = rct.ParseHostSelection(selection)
		if err != nil {
			fmt.Printf("主机选择解析失败: %v\n", err)
			return
		}
	}

	fmt.Println("\n请输入命令，每行一个命令，输入 'DONE' 完成输入:")
	var commands []string
	for {
		command := rct.ReadInput("")
		if command == "DONE" || command == "完成" {
			break
		}
		if command != "" {
			commands = append(commands, command)
		}
	}
	if len(commands) == 0 {
		fmt.Println("没有输入任何命令")
		return
	}

	fmt.Println("\n执行权限选择:")
	fmt.Println("1. 普通用户执行")
	fmt.Println("2. Root用户执行")

	privilegeChoice := rct.ReadInput("请选择执行权限 (1-2): ")
	var useRoot bool

	switch privilegeChoice {
	case "1":
		useRoot = false
		fmt.Println("使用普通用户权限执行")
	case "2":
		useRoot = true
		fmt.Println("使用root权限执行")
	default:
		fmt.Println("无效选择，默认使用普通用户权限执行")
		useRoot = false
	}

	fmt.Printf("正在选定主机上执行 %d 个命令\n", len(commands))

	allResults := rct.ExecuteMultipleCommandsOnSelectedHosts(hostIDs, commands, useRoot)
	rct.PrintMultipleResults(allResults, commands)
}

// handleConfig 处理配置选项
func (rct *RemoteControlTool) handleConfig() {
	fmt.Println("\n配置选项:")
	fmt.Printf("当前自动确认状态: %t\n", rct.config.AutoConfirm)

	autoConfirmInput := rct.ReadInput("是否启用自动确认? (y/n): ")

	if strings.ToLower(autoConfirmInput) == "y" || strings.ToLower(autoConfirmInput) == "yes" {
		rct.config.AutoConfirm = true
	} else {
		rct.config.AutoConfirm = false
	}

	saveConfig(rct.config)
	fmt.Printf("配置已更新，自动确认状态: %t\n", rct.config.AutoConfirm)
}




